package online.inote.common.shiro;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import online.inote.common.utils.CollectionUtils;
import online.inote.modules.user.entity.RoleEntity;
import online.inote.modules.user.entity.UserEntity;
import online.inote.modules.user.service.PermissionService;
import online.inote.modules.user.service.RoleService;
import online.inote.modules.user.service.UserService;

/**
 * <p>
 * Desc: 
 * </p>
 *
 * @author Sui
 * @created: 2017年12月3日 下午9:55:17
 * @version 1.0
 */
public class ShiroRealm extends AuthorizingRealm {

	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private PermissionService permissionService;
	
	/**
	 * 认证回调函数,登录时调用.
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
			throws AuthenticationException {
		
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		UserEntity user = userService.selectByFieldEqual("username", token.getUsername());
		
		if (user == null) return null;
		
		return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
	}

	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		UserEntity user = (UserEntity) principals.getPrimaryPrincipal();
		
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		
		// 加载用户的roles
		List<RoleEntity> rolesList = roleService.hasRoles(user.getId());
		
		if (!CollectionUtils.isEmpty(rolesList)) {
			List<String> stringRoles = new ArrayList<>(rolesList.size());
			Set<String> roleIds = new HashSet<>(rolesList.size());
			
			rolesList.forEach(role -> {
				stringRoles.add(role.getName());
				roleIds.add(role.getId());
			});
			
			info.addRoles(stringRoles);
			
			// 加载用户的permissions
			// 用户的permission分两部分, 用户拥有的角色的permission和用户直接拥有的permission
			List<String> permissionsList = permissionService.hasPermissionValue(roleIds);
			
			if (!CollectionUtils.isEmpty(permissionsList)) {
				info.setStringPermissions(new HashSet<String>(permissionsList));
			}
		}
		
		return info;
	}
}